package com.pudutech.bluetoothdemo

import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothGatt
import android.bluetooth.BluetoothGattCallback
import android.bluetooth.BluetoothProfile
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import com.pudutech.bluetoothdemo.bluetooth.BluetoothUtils
import com.pudutech.bluetoothdemo.bluetooth.ClientSocket
import kotlinx.android.synthetic.main.activity_client.*
import java.util.*

class ClientActivity : AppCompatActivity() {
    var TAG = "ClientActivity"

    var mac1 = "22:22:D5:3D:09:00"   //Server
    var currentDevice: BluetoothDevice? = null
    var mClientSocket: ClientSocket?=null


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_client)
//        //注册广播
//        BluetoothUtils.registerBluetoothReceiver(this,mBroadcastReceiver)
//        //开启蓝牙扫描
//        BluetoothUtils.getBluetoothAdapter(this).startDiscovery()
        //已配对 设备列表
        val pairedDevices: Set<BluetoothDevice>? =
            BluetoothUtils.getBluetoothAdapter(this).bondedDevices
        pairedDevices?.forEach { device ->
            if (mac1 == device.address) {
                currentDevice = device
                bondAndConnect()
            }
        }

        sendBt.setOnClickListener {
            mClientSocket?.sendMessageHandle(sendEt?.text.toString())
        }

        backBt.setOnClickListener {
            finish()
        }
    }

    /**
     * 配对蓝牙  连接蓝牙
     */
    private fun bondAndConnect(){
//        //蓝牙配对
//        currentDevice?.createBond()
        //蓝牙连接监听
        currentDevice?.connectGatt(this, false, object : BluetoothGattCallback() {
            override fun onConnectionStateChange(gatt: BluetoothGatt?, status: Int, newState: Int) {
                super.onConnectionStateChange(gatt, status, newState)
                Log.v(TAG, "------连接状态 $newState")
                if (newState == BluetoothProfile.STATE_CONNECTED) {//已连接
                    connectStatustv.text = "已连接"
//                    BluetoothUtils.startClientThread(currentDevice!!)
                    mClientSocket=ClientSocket(this@ClientActivity,currentDevice)
                }
                // 接受到设备断开的状态后，还要手动调用 close()，否则可能出现连接未断开导致的重连失败等问题;
                if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                    gatt?.close()
                    connectStatustv.text = "断开连接"
                }
                if (newState == BluetoothProfile.STATE_CONNECTING) {
                    //设备在连接中
                    connectStatustv.text = "正在连接中..."
                }
            }
        })
    }

    private var mBroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val action: String? = intent.action
            when (action) {
                BluetoothDevice.ACTION_FOUND -> { //发现新设备连接
                    val device: BluetoothDevice? =
                        intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
                    Log.v(TAG, "------发现新设备连接 ${device?.name}  ${device?.address}")
                    device?.let {
                        if (mac1 == it.address) {
                            Log.v(TAG, "------找到需连接设备 ${device?.name}  ${device?.address}")
                            //停止蓝夜扫描
                            BluetoothUtils.getBluetoothAdapter(this@ClientActivity)
                                ?.cancelDiscovery()
                            currentDevice=device
                            //蓝牙配对
                            bondAndConnect()
                        }
                    }
                }
                BluetoothDevice.ACTION_BOND_STATE_CHANGED -> {
                    val device: BluetoothDevice? =
                        intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
                    var pairingResult: String? = null
                    when (device?.bondState) {
                        BluetoothDevice.BOND_BONDING -> {
                            //正在配对......
                            pairingResult = "寻找配对   正在配对......"
                        }
                        BluetoothDevice.BOND_BONDED -> {
                            //完成配对
                            //startMessageTest(device)
                            pairingResult = "寻找配对   完成配对"
                            //当前配对的  device
                            currentDevice = device
                        }
                        BluetoothDevice.BOND_NONE -> {
                            //取消配对
                            pairingResult = "寻找配对   取消配对"
                        }
                    }
                    connectStatustv?.text = pairingResult
                    Log.v(TAG, "------$pairingResult")
                }
            }
        }
    }


    override fun onDestroy() {
        super.onDestroy()
//        BluetoothUtils.shutdownClient()
//        BluetoothUtils.unregisterReceiver(this,mBroadcastReceiver)
        mClientSocket?.close()
    }
}